import * as Blockly from 'blockly/core'
import { Message } from 'element-ui'
// 创建积木
Blockly.Blocks['controls_map'] = {
  init: function () {
    var that = this
    this.setStyle('loop_blocks')
    const dropdown = new Blockly.FieldDropdown(
      [['map遍历', 'map'], ['forEach遍历', 'forEach']])
    dropdown.setValidator(function (value) {
      const oldValue = that.getFieldValue('METHOD')
      if (that?.previousConnection?.targetConnection && oldValue !== value) {
        Message({
          message: '该选项不支持当前连接，前先断开连接再选择',
          type: 'warning'
        })
        return null
      }
      if (value === 'map') {
        that.setPreviousStatement(false)
        that.setNextStatement(false)
        that.setOutput(true, null)
      } else {
        that.setOutput(false, null)
        that.setPreviousStatement(true)
        that.setNextStatement(true)
      }
    })

    this.appendValueInput('LIST')
      .setCheck('Array')
      .appendField(dropdown, 'METHOD')
      .appendField('列表')
    this.appendValueInput('LOOP_ITEM')
      .setCheck('params_builtin')
      .appendField('的每一项')

    this.appendValueInput('LOOP_INDEX')
      .setCheck('params_builtin')
      .appendField('索引')
    this.appendStatementInput('DO').appendField('执行')
    this.setOutput(true, 'Array')
    this.setTooltip('使用map遍历数组')
    this.setInputsInline(true)
  }
}
Blockly.JavaScript['controls_map'] = function (block) {
  const method = block.getFieldValue('METHOD')
  const list = Blockly.JavaScript.valueToCode(block, 'LIST',
    Blockly.JavaScript.ORDER_FUNCTION_CALL) || '[]'
  const item = Blockly.JavaScript.valueToCode(block, 'LOOP_ITEM',
    Blockly.JavaScript.ORDER_FUNCTION_CALL)
  const index = Blockly.JavaScript.valueToCode(block, 'LOOP_INDEX',
    Blockly.JavaScript.ORDER_FUNCTION_CALL)
  const body = Blockly.JavaScript.statementToCode(block, 'DO')
  const code = `${list}.${method}((${item}, ${index}) => {\n${body}})`
  if (block.outputConnection) {
    return [code, Blockly.JavaScript.ORDER_COMMA]
  } else {
    return code + '\n'
  }
}
